//
//  Day02ViewController.swift
//  SwiftDemo
//
//  Created by zhudeshuai on 2018/9/26.
//  Copyright © 2018年 zhudeshuai. All rights reserved.
//

import Foundation
import UIKit
class Day02ViewController: BaseViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        contentView.backgroundColor = UIColor.white
        layout01()
    }
    
     let showLabel = UILabel()
    
    //SnapKit布局一
    func layout01() {
        let topBox = UIView()
        topBox.backgroundColor = UIColor.brown
        contentView.addSubview(topBox)
        topBox.snp.makeConstraints{(make) in
            make.top.left.right.equalTo(contentView)
            make.bottom.equalTo(contentView.snp.centerY).offset(0)
        }
       
        showLabel.text = "0"
        showLabel.font = UIFont.systemFont(ofSize: 30)
        showLabel.textColor = UIColor.black
        topBox.addSubview(showLabel)
        showLabel.snp.makeConstraints{(make) in
            make.centerX.equalTo(topBox)
            make.centerY.equalTo(topBox)
        }
        
        //开始
        let startView = UIButton()
        startView.setTitle("start", for: .normal)
        startView.backgroundColor = UIColor.green
        contentView.addSubview(startView)
        startView.addTarget(self, action: #selector(onStart), for: .touchUpInside)
        startView.snp.makeConstraints{(make) in
            make.top.equalTo(topBox.snp.bottom)
            make.left.bottom.equalToSuperview()
            make.right.equalTo(contentView.snp.centerX).offset(0)
        }
        
        //结束
        let endView = UIButton()
        endView.setTitle("end", for: .normal)
        endView.backgroundColor = UIColor.red
        contentView.addSubview(endView)
        endView.addTarget(self, action: #selector(onEnd), for: .touchUpInside)
        endView.snp.makeConstraints{(make) in
            make.top.equalTo(topBox.snp.bottom)
            make.bottom.right.equalToSuperview()
            make.left.equalTo(contentView.snp.centerX)
        }
        
    }
    
    var timer = Timer()
    var lastNumber:Double = 0
    @objc func onStart(){
        if(!self.timer.isValid){
            self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true,block: {(Timer) in
                self.lastNumber = self.lastNumber + 0.1
                self.showLabel.text = String(format: "%.1f", self.lastNumber)
            })
        }
        

    }
    
    @objc func onEnd(){
        self.timer.invalidate()
    }
}
